package com.xiaoniu.lib_keleim.channel;

import android.text.TextUtils;


import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.HashSet;

//public class MqttClient {
//
//    private static MqttClient mMqttClient;
//    private MqttAndroidClient mqttAndroidClient;
//    private final String serverUri = "tcp://192.168.0.106:1883";
//    private String clientId = "";
//    HashSet<String> mTopicList = new HashSet<>();
//    public static MqttClient getInstance(){
//        if (mMqttClient==null) {
//            mMqttClient = new MqttClient();
//        }
//        return mMqttClient;
//    }
//
//    public void connect(){
//        clientId = "clientId" + System.currentTimeMillis();
//
//        mqttAndroidClient = new MqttAndroidClient(IMClient.getManager().getContext(), serverUri, clientId);
//        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
//            @Override
//            public void connectComplete(boolean reconnect, String serverURI) {
//
//                if (reconnect) {
//                    LogUtils.d("Reconnected to : " + serverURI);
//                    // Because Clean Session is true, we need to re-subscribe
//                    subscribeToAllTopic();
//                } else {
//                    LogUtils.d("Connected to: " + serverURI);
//                }
//            }
//
//            @Override
//            public void connectionLost(Throwable cause) {
//                LogUtils.d("The Connection was lost.");
//            }
//
//            @Override
//            public void messageArrived(String topic, MqttMessage message) throws Exception {
//                String receiveMessage = new String(message.getPayload());
//                LogUtils.d("Incoming message: " + new String(message.getPayload()));
//                onReceiveMessage(topic,receiveMessage);
//            }
//
//            @Override
//            public void deliveryComplete(IMqttDeliveryToken token) {
//                LogUtils.d("deliveryComplete: ");
//            }
//        });
//
//        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
//        mqttConnectOptions.setAutomaticReconnect(true);
//        mqttConnectOptions.setCleanSession(false);
//        mqttConnectOptions.setKeepAliveInterval(60);
//
//        try {
//            LogUtils.d("Connecting to " + serverUri);
//            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
//                @Override
//                public void onSuccess(IMqttToken asyncActionToken) {
//                    LogUtils.d("onSuccess connect ");
//                    DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
//                    disconnectedBufferOptions.setBufferEnabled(true);
//                    disconnectedBufferOptions.setBufferSize(100);
//                    disconnectedBufferOptions.setPersistBuffer(false);
//                    disconnectedBufferOptions.setDeleteOldestMessages(false);
//                    mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
//                    subscribeToTopic("sys/all");
//                }
//
//                @Override
//                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
//                    LogUtils.d("Failed to connect to: " + serverUri);
//                    LogUtils.d("Failed to connect to: " + exception.getMessage() +" "+exception.getCause());
//                }
//            });
//
//
//        } catch (MqttException ex){
//            ex.printStackTrace();
//        }
//    }
//
//    private void onReceiveMessage(String topic,String receiveMessage) {
//        BaseMessage mBaseMessage = GsonUtil.fromJson(receiveMessage, BaseMessage.class);
//        //会话类型 聊天室:0 私聊 :1
//        if (mBaseMessage.conversationType == 0) {
//            if (mBaseMessage.targetId != IMClient.getManager().getTargetRoomID()) {
//                return;
//            }
//            MessageParseUtil.parseMessage(mBaseMessage,receiveMessage);
//        }
//    }
//
//    public void subscribeToAllTopic(){
//        for (String topic : mTopicList) {
//            subscribeToTopic(topic);
//        }
//    }
//
//    public void subscribeToTopic(String subscriptionTopic){
//        try {
//            LogUtils.d("subscribeToTopic! "+subscriptionTopic);
//            mTopicList.add(subscriptionTopic);
//            mqttAndroidClient.subscribe(subscriptionTopic, 0, subscriptionTopic, new IMqttActionListener() {
//                @Override
//                public void onSuccess(IMqttToken asyncActionToken) {
//                    LogUtils.d("Subscribed! "+subscriptionTopic);
//                }
//                @Override
//                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
//                    LogUtils.d("Failed to subscribe");
//                }
//            });
//        } catch (MqttException ex){
//            LogUtils.d("Exception whilst subscribing");
//            ex.printStackTrace();
//        }
//    }
//
//    public void unSubscribeTopic(String subscriptionTopic){
//        LogUtils.d("unSubscribeTopic! "+subscriptionTopic);
//        if (mqttAndroidClient==null || TextUtils.isEmpty(subscriptionTopic)) {
//            return;
//        }
//        mTopicList.remove(subscriptionTopic);
//        try {
//            mqttAndroidClient.unsubscribe(subscriptionTopic);
//        } catch (MqttException e) {
//            e.printStackTrace();
//        }
//    }
//
//    public void publishMessage(String publishTopic,String payload){
//        if (mqttAndroidClient==null || TextUtils.isEmpty(publishTopic) || TextUtils.isEmpty(payload)) {
//            return;
//        }
//        try {
//            MqttMessage message = new MqttMessage();
//            message.setPayload(payload.getBytes());
//            mqttAndroidClient.publish(publishTopic, message);
//            LogUtils.d("Message Published");
//            if(!mqttAndroidClient.isConnected()){
//                mqttAndroidClient.connect();
//                LogUtils.d(mqttAndroidClient.getBufferedMessageCount() + " messages in buffer.");
//            }
//        } catch (MqttException e) {
//            LogUtils.d("Error Publishing: " + e.getMessage());
//            e.printStackTrace();
//        } catch (Exception e) {
//            LogUtils.d("Error Publishing: " + e.getMessage());
//            e.printStackTrace();
//        }
//    }
//
//}
